package com.pug.controller.user;

import com.pug.bo.KssUserBo;
import com.pug.config.middle.minio.MinIOConfig;
import com.pug.config.middle.minio.MinIoUploadService;
import com.pug.controller.APIBaseController;
import com.pug.entity.KssUser;
import com.pug.service.user.IUserService;
import com.pug.service.weixin.WeixinData;
import com.pug.threadlocal.UserThrealLocal;
import com.pug.utils.fn.asserts.Vsserts;
import com.pug.vo.KssUserSettingVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author 飞哥
 * @Title: 学相伴出品
 * @Description: 飞哥B站地址：https://space.bilibili.com/490711252
 * 记得关注和三连哦！
 * @Description: 我们有一个学习网站：https://www.kuangstudy.com
 * @date 2022/3/16$ 23:56$
 */
@Api(tags = "用户中心个人设置")
@RestController
@RequiredArgsConstructor
public class UserSettingController extends APIBaseController {

    private final IUserService userService;
    private final MinIoUploadService minIoUploadService;
    private final MinIOConfig minIOConfig;


    @ApiOperation("修改用户头像接口")
    @PostMapping("/user/modifty/avatar/{userid}")
    public KssUserBo updateAvatar(@PathVariable("userid") Long userId,
                                  @RequestParam("filename") String filename,
                                  @RequestParam("bucketname") String bucketname,
                                  MultipartFile file) throws Exception {
        Vsserts.isNullEx(userId, "没有找到修改用户");
        //给上传的头像取一个名字，不建议使用原始图片作为图片名，
        // 为什么：上传都喜欢把文件名用一些随机数或者uuid获取写工具方法重新成功。防止冲突
        // 比如A 用户本地电脑：1.jpg  B 比如B 用户本地电脑：1.jpg
        long fileSize = file.getSize();
        String contentType = file.getContentType();
        // 过滤判断
        // 压缩方法
        String fileName = null;
        if(Vsserts.isNotEmpty(filename)){
            fileName = filename;
        }else{
            String oldname = file.getOriginalFilename();
            String ext = oldname.substring(oldname.lastIndexOf("."));
            fileName = UUID.randomUUID().toString() + ext;
        }

        if(Vsserts.isEmpty(bucketname)){
            bucketname = minIOConfig.getBucketName();
        }

        minIoUploadService.createBucket(bucketname);
        minIoUploadService.uploadFile(bucketname, fileName, file.getInputStream());
        String imgUrl = minIOConfig.getFileHost()
                + "/"
                + bucketname
                + "/"
                + fileName;

        KssUser kssUser = new KssUser();
        kssUser.setId(userId);
        kssUser.setAvatar(imgUrl);
        userService.saveOrUpdate(kssUser);

        // 返回
        KssUserBo kssUserBo = new KssUserBo();
        kssUserBo.setAvatar(imgUrl);
        return kssUserBo;
    }

    @ApiOperation("修改用户背景")
    @PostMapping("/user/modifty/bgimg/{userid}")
    public KssUserBo updateBgImg(@PathVariable("userid") Long userId,
                                 @RequestParam("bucketname") String bucketname,
                                 @RequestParam("filename") String filename,
                                 MultipartFile file) throws Exception {
        Vsserts.isNullEx(userId, "没有找到修改用户");
        String fileName = null;
        if(Vsserts.isNotEmpty(filename)){
            fileName = filename;
        }else{
            String oldname = file.getOriginalFilename();
            String ext = oldname.substring(oldname.lastIndexOf("."));
            fileName = UUID.randomUUID().toString() + ext;
        }
        if(Vsserts.isEmpty(bucketname)){
            bucketname = minIOConfig.getBucketName();
        }
        minIoUploadService.createBucket(bucketname);
        minIoUploadService.uploadFile(bucketname, fileName, file.getInputStream());
        String imgUrl = minIOConfig.getFileHost()
                + "/"
                + bucketname
                + "/"
                + fileName;
        KssUser kssUser = new KssUser();
        kssUser.setId(userId);
        kssUser.setBgImg(imgUrl);
        userService.saveOrUpdate(kssUser);
        // 返回
        KssUserBo kssUserBo = new KssUserBo();
        kssUserBo.setBgImg(imgUrl);
        return kssUserBo;
    }


    @ApiOperation("修改用户其他的信息")
    @PostMapping("/user/modifty/info")
    public KssUserBo updateUserInfo(@RequestBody KssUserSettingVo userSettingVo) throws Exception {
        Vsserts.isNullEx(userSettingVo.getUserId(), "没有找到修改用户");
        KssUser kssUser = userService.getById(userSettingVo.getUserId());
        BeanUtils.copyProperties(userSettingVo,kssUser);
        kssUser.setId(userSettingVo.getUserId());
        userService.updateById(kssUser);
        // 返回
        KssUserBo kssUserBo = new KssUserBo();
        BeanUtils.copyProperties(kssUser,kssUserBo);
        return kssUserBo;
    }


    @ApiOperation("同步微信授权的用户信息")
    @PostMapping("/user/update/weixin")
    public KssUserBo updateweixinuserinfo(@RequestBody WeixinData weixinData) throws Exception {
        KssUser kssUser = UserThrealLocal.get();//这里确实完整的信息 20 update
        KssUser modifyUser = new KssUser();
        modifyUser.setId(kssUser.getId());
        modifyUser.setNickname(weixinData.getNickName());
        modifyUser.setAvatar(weixinData.getAvatarUrl());
        modifyUser.setCountry(weixinData.getCountry());
        modifyUser.setProvince(weixinData.getProvince());
        modifyUser.setCity(weixinData.getCity());
        modifyUser.setSex(Integer.parseInt(weixinData.getGender()));
        boolean b = userService.updateById(modifyUser);
        if(b) {
            // 返回
            KssUserBo kssUserBo = new KssUserBo();
            BeanUtils.copyProperties(modifyUser, kssUserBo);
            return kssUserBo;
        }
        return null;
    }

}
